<script setup>
import { Message, MessageBox } from 'element-ui';
import { cloneDeep, forEach, map } from 'lodash-es';
import dayjs from 'dayjs';
import { rulesPattern } from '@/utils/tools';
import {
  getEnergyList,
  getProjectByIn,
  addProject,
  updateTGProject,
  deleteProject,
  getProHistory,
} from '@/api/index.js';
import { useRequest, useWatch } from '@/hooks';

const props = defineProps({
  enterprise: { type: Object, default: () => null },
});
const emit = defineEmits(['projectData']);
const Forms = ref(null);
const title = ref('');
const queryParams = ref({
  startTime: null,
  endTime: null,
  contractAmount: null,
  enEnergyTypes: null,
  contractType: null,
  projectCode: null,
  ensureType: null,
});
const rules = ref({
  startTime: [{ required: true, message: '请选择托管服务年限', trigger: 'change' }],
  contractAmount: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }],
  enEnergyTypes: [{ required: true, message: '请选择托管能源类型', trigger: 'change' }],
  contractType: [{ required: true, message: '请选择托管合同类型', trigger: 'change' }],
  ensureType: [{ required: true, message: '请选择', trigger: 'change' }],
});
const dateRange = ref([]);
const contractTypeList = ref([
  {
    value: 'CONVENTION',
    label: '能源费用托管型',
  },
  {
    value: 'SHARE',
    label: '节能效益分享型',
  },
  {
    value: 'ENSURE',
    label: '节能量保证型',
  },
]);
const ensureForm = ref(null);
const shareForm = ref(null);
const ensureTypeList = ref([
  {
    key: 'CONSERVATIONVALUE',
    label: '节能量(日)',
  },
  {
    key: 'CONSERVATIONRATIO',
    label: '节能率(日)',
  },
]);
const jnxyGroup = ref({
  dateRange: [],
  valueRate: null,
  dailyRate: null,
});
const jnlGroup = ref({
  dateRange: [],
  dailyRate: null, //日服务费
});
const jnlList = ref([]);
const jnxyList = ref([]);
const jnlRules = ref({
  dateRange: [{ required: true, message: '请选择执行时段', trigger: 'change' }],
  // 电Amount: [
  //   { required: true, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 电Price: [
  //   { required: false, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 水Amount: [
  //   { required: true, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 水Price: [
  //   { required: false, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 天然气Amount: [
  //   { required: true, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 天然气Price: [
  //   { required: false, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 暖Amount: [
  //   { required: true, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 暖Price: [
  //   { required: false, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 油Amount: [
  //   { required: true, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  // 油Price: [
  //   { required: false, message: '请输入', trigger: 'blur' },
  //   {
  //     pattern: rulesPattern.remainder2,
  //     message: '请输入小数点后2位正数',
  //     trigger: 'blur',
  //   },
  // ],
  dailyRate: [
    { required: true, message: '请输入日服务费用金额', trigger: 'blur' },
    {
      pattern: rulesPattern.remainder2,
      message: '请输入小数点后2位正数',
      trigger: 'blur',
    },
  ],
});
const jnxyRules = ref({
  dateRange: [{ required: true, message: '请选择执行时段', trigger: 'change' }],
  valueRate: [
    { required: true, message: '请输入分享收益比例', trigger: 'blur' },
    {
      pattern: rulesPattern.hundred,
      message: '请输入小数点后2位正数且不超过100',
      trigger: 'blur',
    },
  ],
  dailyRate: [
    { required: false, message: '请输入', trigger: 'blur' },
    {
      pattern: rulesPattern.remainder2,
      message: '请输入小数点后2位正数',
      trigger: 'blur',
    },
  ],
});
const visible = ref(false);
const dialogParams = ref({
  inId: '',
  projectCodeP: '',
  pageNum: 1,
  pageSize: 2,
});
const recordData = ref(null);

const typeList = ref([]);
useRequest(getEnergyList, {
  defaultParams: [{ pageNum: 1, pageSize: 10 }],
  onSuccess: res => {
    typeList.value = res.rows;
  },
});
const [res, loading, run] = useRequest(getProjectByIn, {
  manual: true,
  onSuccess: res => {
    loading.value = false;
    if (res.code === 200) {
      let obj = cloneDeep(res.data);
      emit('projectData', obj);
      title.value = obj && obj?.projectCode?.length > 0 ? '编辑' : '新增';
      dateRange.value = [obj?.startTime ?? '', obj?.endTime ?? ''];
      queryParams.value.startTime = obj?.startTime;
      queryParams.value.endTime = obj?.endTime;
      queryParams.value.contractAmount = obj?.contractAmount;
      queryParams.value.projectCode = obj?.projectCode;
      // dialogParams.value.projectCodeP = obj?.projectCodeP;
      queryParams.value.enEnergyTypes = obj?.enEnergyTypes.map(n => {
        return n.id;
      });
      queryParams.value.contractType = obj?.contractType;

      if (queryParams.value.contractType === 'ENSURE') {
        queryParams.value.ensureType = obj.enProjectContractTypes?.[0]?.[0]?.ensureType ?? 'CONSERVATIONVALUE';
        let arr = [];
        forEach(obj.enProjectContractTypes, n => {
          let obj2 = {};
          forEach(n, el => {
            if (queryParams.value.enEnergyTypes.indexOf(Number(el.keyTypeId)) > -1) {
              forEach(obj?.enEnergyTypes, item => {
                if (Number(el.keyTypeId) === item.id) {
                  obj2[`${item.energyName}Amount`] = el.valueAmount;
                  obj2[`${item.energyName}Price`] = el.valuePrice;
                  obj2.dateRange = [el?.startTime, el?.endTime];
                  obj2.dailyRate = el.dailyRate;
                }
              });
            }
          });
          arr.push(obj2);
        });
        nextTick(() => {
          jnlList.value = cloneDeep(arr);
        });
      } else if (queryParams.value.contractType === 'SHARE') {
        queryParams.value.ensureType = null;
        let arr = [];
        forEach(obj.enProjectContractTypes, item => {
          forEach(item, el => {
            let obj2 = {};
            obj2.dateRange = [el?.startTime, el?.endTime];
            obj2.valueRate = el.valueRate;
            obj2.dailyRate = el.dailyRate;
            arr.push(obj2);
          });
        });
        nextTick(() => {
          jnxyList.value = cloneDeep(arr);
        });
      } else if (queryParams.value.contractType === 'CONVENTION') {
        queryParams.value.ensureType = null;
      }
    }
  },
  onError: () => {
    queryParams.value = {
      startTime: null,
      endTime: null,
      contractAmount: null,
      enEnergyTypes: null,
      contractType: null,
      projectCode: null,
      ensureType: null,
    };
    dateRange.value = [];
    jnlList.value = [];
    jnxyList.value = [];
  },
});

const [, , addRun] = useRequest(addProject, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      run({ inId: props.enterprise?.enterpriseCode, projectType: 'TG' });
    } else {
      Message.error(res.msg);
    }
  },
});
const [, , editRun] = useRequest(updateTGProject, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      run({ inId: props.enterprise?.enterpriseCode, projectType: 'TG' });
    } else {
      Message.error(res.msg);
    }
  },
});
const [, , deleteRun] = useRequest(deleteProject, {
  manual: true,
});
const [record, loading2, recordRun] = useRequest(getProHistory, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      recordData.value = forEach(res.rows, n => {
        n.contractType = map(contractTypeList.value, el => {
          return el.value === n.contractType ? el.label : '';
        });
        n.contractType = n.contractType.toString().replaceAll(',', '');
        n.enEnergyTypes = map(n.enEnergyTypes, (el, index) => {
          return el.energyName;
        });
        // forEach(n.enProjectContractTypes,el=>{
        //   forEach(el,item=>{

        //   })
        // })
      });
    }
  },
});
const changeDate = val => {
  queryParams.value.startTime = val?.[0] ?? null;
  queryParams.value.endTime = val?.[1] ?? null;
  if (jnlList.value?.length > 0) {
    jnlList.value = [];
  }
  if (jnxyList.value?.length > 0) {
    jnxyList.value = [];
  }
};
const changeCtType = val => {
  // if (queryParams.value.enEnergyTypes?.length < 1 || queryParams.value.startTime?.length < 1) {
  //   Message.warning('请先填写表单其他项');
  //   queryParams.value.contractType = null;
  // } else {
  //   if (val === '节能量保证型') {
  //   }
  // }
};
const addJnl = () => {
  let obj = cloneDeep(jnlGroup.value);
  forEach(typeList.value, n => {
    if (queryParams.value.enEnergyTypes.indexOf(n.id) > -1) {
      obj[`${n.energyName}Amount`] = '';
      obj[`${n.energyName}Price`] = '';
    }
  });
  jnlList.value.unshift(obj);
};
const addJnxy = () => {
  jnxyList.value.unshift(cloneDeep(jnxyGroup.value));
};
const deleteItem = type => {
  if (type === 'SHARE') {
    jnxyList.value.splice(0, 1);
  } else if (type === 'ENSURE') {
    jnlList.value.splice(0, 1);
  }
};
const pickerOptions = computed(() => {
  return {
    disabledDate: time => {
      if (dateRange.value.length > 0) {
        return dayjs(time) < dayjs(dateRange.value[0]) || dayjs(time) > dayjs(dateRange.value[1]);
      }
    },
  };
});
const changetime = (val, index, type) => {
  let dateRanges;
  if (type === 'ENSURE') {
    dateRanges = map(jnlList.value, n => {
      return n.dateRange;
    });
  } else if (type === 'SHARE') {
    dateRanges = map(jnxyList.value, n => {
      return n.dateRange;
    });
  }
  dateRanges.sort((a, b) => new Date(a[0]) - new Date(b[0]));
  // 遍历日期范围数组，判断是否存在重叠
  let hasOverlap = false;
  for (let i = 0; i < dateRanges.length - 1; i++) {
    const currentRange = dateRanges[i];
    const nextRange = dateRanges[i + 1];
    if (new Date(currentRange[1]) >= new Date(nextRange[0])) {
      hasOverlap = true;
      break;
    }
  }
  if (hasOverlap) {
    Message.warning('执行时段不可交叉重复');
    if (type === 'ENSURE') {
      jnlList.value[index].dateRange = [];
    } else if (type === 'SHARE') {
      jnxyList.value[index].dateRange = [];
    }
  }
};
const handleSave = () => {
  // loading.value = true;
  Forms.value.validate(valid => {
    if (valid) {
      let params = {
        inId: props.enterprise?.enterpriseCode,
        projectName: props.enterprise?.enterpriseName,
        entrustStage: props.enterprise?.status,
        projectType: 'TG',
        ...queryParams.value,
        enProjectContractTypes: [],
        isContractType: res.value?.contractType != queryParams.value.contractType ? 1 : null,
      };
      params.enEnergyTypes = map(params.enEnergyTypes, n => {
        return { id: n };
      });
      if (queryParams.value.contractType === 'SHARE') {
        let total = 0;
        forEach(shareForm.value, n => {
          n.validate(valid => {
            if (valid) {
              total = total + 1;
            } else {
              return false;
            }
          });
        });
        if (total === shareForm.value?.length) {
          let arr = [];
          forEach(jnxyList.value, n => {
            let obj = {};
            obj.startTime = n.dateRange[0];
            obj.endTime = n.dateRange[1];
            obj.valueRate = n.valueRate;
            obj.dailyRate = n.dailyRate;
            obj.ensureType = 'RATIO';
            arr.push([obj]);
          });
          params.enProjectContractTypes = arr;
          MessageBox.confirm('请确认信息无误', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          }).then(() => {
            if (title.value === '编辑') {
              editRun(params);
            } else {
              addRun(params);
            }
          });
        }
      } else if (queryParams.value.contractType === 'ENSURE') {
        let total = 0;
        forEach(ensureForm.value, n => {
          n.validate(valid => {
            if (valid) {
              total = total + 1;
            } else {
              return false;
            }
          });
        });
        if (total === ensureForm.value.length) {
          let arr = [];
          let boo = false;
          forEach(jnlList.value, n => {
            let arr2 = [];
            forEach(queryParams.value.enEnergyTypes, el => {
              let obj = {};
              obj.ensureType = queryParams.value.ensureType;
              obj.startTime = n.dateRange[0];
              obj.endTime = n.dateRange[1];
              let items = typeList.value.find(item => item.id === el);
              obj.keyTypeId = el;
              obj.valueAmount = n[`${items.energyName}Amount`];
              obj.valuePrice = n[`${items.energyName}Price`];
              obj.dailyRate = n.dailyRate;
              obj.id = el;
              arr2.push(obj);
            });
            for (let i = 0; i < arr2.length - 1; i++) {
              if (Number(arr2[i]?.valuePrice) > 0 && Number(arr2[i + 1]?.valuePrice) > 0) {
              } else if (Number(arr2[i]?.valuePrice) == 0 && Number(arr2[i + 1]?.valuePrice) == 0) {
              } else {
                boo = true;
                Message.error('节能量单价非必填，填某一个其他必填');
                return;
              }
            }
            arr.push(arr2);
          });
          if (!boo) {
            params.enProjectContractTypes = arr;
            MessageBox.confirm('请确认信息无误', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning',
            }).then(() => {
              if (title.value === '编辑') {
                editRun(params);
              } else {
                addRun(params);
              }
            });
          }
        }
      } else if (queryParams.value.contractType === 'CONVENTION') {
        MessageBox.confirm('请确认信息无误', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(() => {
          if (title.value === '编辑') {
            editRun(params);
          } else {
            addRun(params);
          }
        });
      }
    } else {
      return false;
    }
  });
};
const showRecord = () => {
  visible.value = true;
  dialogParams.value.pageNum = 1;
  dialogParams.value.pageSize = 2;
  dialogParams.value.inId = props.enterprise?.enterpriseCode;
  dialogParams.value.projectCodeP = queryParams.value.projectCode;
  recordRun(dialogParams.value);
};
const getList = e => {
  dialogParams.value.pageNum = e.page;
  dialogParams.value.pageSize = e.limit;
  recordRun(dialogParams.value);
};
useWatch(
  () => queryParams.value.enEnergyTypes,
  (n, o) => {
    jnlList.value = [];
    jnxyList.value = [];
    addJnl();
    addJnxy();
  },
  { deep: true },
);
useWatch(
  () => queryParams.value.contractType,
  n => {
    if (n) {
      if (queryParams.value.enEnergyTypes?.length < 1 || queryParams.value.startTime?.length < 1) {
        Message.warning('请先填写表单其他项');
        queryParams.value.contractType = null;
      } else {
        if (n === 'ENSURE') {
          queryParams.value.ensureType = queryParams.value?.ensureType
            ? queryParams.value.ensureType
            : 'CONSERVATIONVALUE';
        } else if (n === 'SHARE') {
        } else if (n === 'CONVENTION') {
        }
      }
    }
  },
);
useWatch(
  () => props.enterprise,
  n => {
    if (n) {
      run({ inId: n?.enterpriseCode, projectType: 'TG' });
      // run({ inId: 'tdInId', projectType: 'TG' });
    }
  },
  { deep: true, immediate: true },
);
</script>
<template>
  <div class="u-h100" style="overflow-y: scroll">
    <el-form
      :model="queryParams"
      ref="Forms"
      :rules="rules"
      size="small"
      label-width="200px"
      class="u-mt20"
      :inline="false"
      v-loading="loading"
    >
      <el-form-item label="托管服务年限：" prop="startTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 230px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate"
        ></el-date-picker>
        <a class="u-primary u-ml10" @click="showRecord">修改记录</a>
        <div class="red">*记录运营开始结束时间</div>
      </el-form-item>
      <el-form-item label="托管投资总额（元）：" prop="contractAmount">
        <el-input
          style="width: 300px"
          placeholder="请输入"
          v-filter-input
          v-model="queryParams.contractAmount"
          clearable
          size="small"
        />
      </el-form-item>
      <br />
      <el-form-item label="托管能源类型：" prop="enEnergyTypes">
        <el-select v-model="queryParams.enEnergyTypes" multiple placeholder="请选择" style="width: 300px">
          <el-option v-for="item in typeList" :key="item.id" :label="item.energyName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item label="托管合同类型：" prop="contractType">
        <el-select v-model="queryParams.contractType" placeholder="请选择" @change="changeCtType" style="width: 300px">
          <el-option
            v-for="item in contractTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item v-if="queryParams.contractType === 'ENSURE'" label="保证：" prop="ensureType">
        <el-select v-model="queryParams.ensureType" placeholder="请选择" style="width: 300px">
          <el-option v-for="dict in ensureTypeList" :key="dict.key" :label="dict.label" :value="dict.key"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="u-pl20" v-if="queryParams.contractType === 'ENSURE'">
      <el-button size="small" type="primary" plain @click="addJnl">添加设置组</el-button>
      <!-- background: #18233e; -->
      <el-form
        v-for="(item, index) in jnlList"
        :key="index"
        ref="ensureForm"
        class="u-p20 u-mt20 u-base-bg"
        :model="item"
        :rules="jnlRules"
        size="small"
        label-width="200px"
        :inline="true"
        label-position="right"
        style="width: 75%"
      >
        <el-form-item label="执行时段：" prop="dateRange">
          <el-date-picker
            v-model="item.dateRange"
            size="small"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="e => changetime(e, index, 'ENSURE')"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="保证：" prop="ensureType">
          <el-select v-model="item.ensureType" placeholder="请选择" style="width: 220px">
            <el-option v-for="dict in ensureTypeList" :key="dict.key" :label="dict.label" :value="dict.key"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <br /> -->
        <div class="red">
          *节能量单价可不填，填某一个，其他必填。节能量单价未填，执行时段内服务费按日服务*执行天数计算收益
        </div>
        <el-form-item
          v-if="Object.keys(item).includes('电Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用电节能率（%）:' : '保证用电节能量（kW.h）：'"
          prop="电Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用电节能率' : '请输入保证用电节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.电Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('电Price')"
          label="节能量单价（kW.h/元）："
          prop="电Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.电Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('水Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用水节能率（%）:' : '保证用水节能量（m³）：'"
          prop="水Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用水节能率' : '请输入保证用水节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.水Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('水Price')"
          label="节能量单价（m³/元）："
          prop="水Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.水Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('天然气Amount')"
          :label="
            queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证天然气节能率（%）:' : '保证天然气节能量（m³）：'
          "
          prop="天然气Amount"
          :rules="[
            {
              required: true,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入保证用天然气节能率'
                  : '请输入保证用天然气节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.天然气Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('天然气Price')"
          label="节能量单价（m³/元）："
          prop="天然气Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.天然气Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('暖Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用热节能率（%）:' : '保证用热节能量（KJ）：'"
          prop="暖Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用热节能率' : '请输入保证用热节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.暖Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('暖Price')"
          label="节能量单价（KJ/元）："
          prop="暖Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.暖Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('油Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用油节能率（%）:' : '保证用油节能量（L）：'"
          prop="油Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用油节能率' : '请输入保证用油节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.油Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('油Price')"
          label="节能量单价（L/元）："
          prop="油Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.油Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('标煤Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用煤节能率（%）:' : '保证用煤节能量（KJ）：'"
          prop="标煤Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用煤节能率' : '请输入保证用煤节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.标煤Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('标煤Price')"
          label="节能量单价（KJ/元）："
          prop="标煤Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.标煤Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('热Amount')"
          :label="queryParams.ensureType === 'CONSERVATIONRATIO' ? '保证用热节能率（%）:' : '保证用热节能量（KJ）：'"
          prop="热Amount"
          :rules="[
            {
              required: true,
              message: queryParams.ensureType === 'CONSERVATIONRATIO' ? '请输入保证用热节能率' : '请输入保证用热节能量',
              trigger: 'blur',
            },
            {
              pattern: queryParams.ensureType === 'CONSERVATIONRATIO' ? rulesPattern.hundred : rulesPattern.remainder2,
              message:
                queryParams.ensureType === 'CONSERVATIONRATIO'
                  ? '请输入小数点后2位正数且不超过100'
                  : '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.热Amount"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          v-if="Object.keys(item).includes('热Price')"
          label="节能量单价（KJ/元）："
          prop="热Price"
          :rules="[
            { required: false, message: '请输入', trigger: 'blur' },
            {
              pattern: rulesPattern.remainder2,
              message: '请输入小数点后2位正数',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.热Price"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="日服务费用（元）：" prop="dailyRate">
          <el-input
            style="width: 220px"
            placeholder="请输入"
            v-filter-input
            v-model="item.dailyRate"
            clearable
            size="small"
          />
        </el-form-item>
        <div v-show="index === 0" class="delete u-df-ct u-base-fg" @click="deleteItem('ENSURE')">
          <i class="el-icon-delete u-mr5"></i>
          删除
        </div>
      </el-form>
    </div>
    <div class="u-pl20" v-if="queryParams.contractType === 'SHARE'">
      <el-button size="small" type="primary" plain @click="addJnxy">添加设置组</el-button>
      <el-form
        v-for="(item, index) in jnxyList"
        :key="index"
        ref="shareForm"
        class="u-p20 u-mt20 u-base-bg itemForm"
        :model="jnxyList[index]"
        :rules="jnxyRules"
        size="small"
        label-width="200px"
        :inline="false"
        label-position="right"
        style="width: 60%"
      >
        <el-form-item label="执行时段：" prop="dateRange">
          <el-date-picker
            v-model="item.dateRange"
            size="small"
            style="width: 70%"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="e => changetime(e, index, 'SHARE')"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="分享收益比例（%）：" prop="valueRate">
          <el-input
            style="width: 70%"
            placeholder="请输入"
            v-filter-input
            v-model="jnxyList[index].valueRate"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="日收益金额（元）：" prop="dailyRate">
          <el-input
            style="width: 70%"
            placeholder="请输入"
            v-filter-input
            v-model="jnxyList[index].dailyRate"
            clearable
            size="small"
          />
          <div class="red">*日收益金额可不填，填写后，执行时段收益按日收益*天数计算</div>
        </el-form-item>
        <div v-show="index === 0" class="delete u-df-ct u-base-fg" @click="deleteItem('SHARE')">
          <i class="el-icon-delete u-mr5"></i>
          删除
        </div>
      </el-form>
    </div>
    <div class="submit"><el-button size="small" type="primary" @click="handleSave">提交</el-button></div>
    <el-dialog :visible.sync="visible" title="修改记录" :append-to-body="true" width="50%">
      <div
        v-loading="loading2"
        v-for="(item, index) in recordData ?? []"
        :key="index"
        class="u-prim-text u-fs14 record"
      >
        <el-form label-position="right" label-width="150px">
          <el-form-item label="修改时间：">
            {{ item?.updateTime ?? '-' }}
            <span class="u-pl20">修改人：{{ item?.createPerson ?? '-' }}</span>
          </el-form-item>
          <el-form-item label="托管服务年限：">
            <el-input
              v-model="item.create11"
              size="small"
              style="width: 80%"
              :placeholder="item.startTime + ' - ' + item.endTime"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="托管合同总额：">
            <el-input v-model="item.contractAmount" size="small" style="width: 80%" :disabled="true" />
          </el-form-item>
          <el-form-item label="托管能源类型：">
            <el-input v-model="item.enEnergyTypes" size="small" style="width: 80%" :disabled="true" />
          </el-form-item>
          <el-form-item label="托管合同类型：">
            <el-input v-model="item.contractType" size="small" style="width: 80%" :disabled="true" />
          </el-form-item>
          <el-form-item v-show="item.contractType == '节能量保证型'" label="保证：">
            <el-input
              v-model="item.ensureType"
              :placeholder="
                item?.enProjectContractTypes?.[0]?.[0]?.ensureType === 'CONSERVATIONRATIO' ? '节能率(日)' : '节能量(日)'
              "
              size="small"
              style="width: 80%"
              :disabled="true"
            />
          </el-form-item>
        </el-form>
        <!-- {{ item.contractType }} -->
        <template v-if="item.contractType == '节能效益分享型'">
          <el-form
            v-for="(el, elInd) in item?.enProjectContractTypes ?? []"
            class="u-p20 u-mt20 u-base-bg"
            :key="elInd"
            label-position="right"
            label-width="180px"
            :inline="true"
          >
            <el-form-item v-for="(types, ind) in el" :key="ind">
              <el-form-item label="执行时段：">
                <el-input
                  v-model="types.time"
                  :placeholder="types.startTime + ' - ' + types.endTime"
                  size="small"
                  :disabled="true"
                  style="width: 500px"
                />
              </el-form-item>
              <br />
              <el-form-item label="分享收益比例（%）：">
                <el-input v-model="types.valueRate" size="small" :disabled="true" style="width: 500px" />
              </el-form-item>
              <br />
              <el-form-item label="日收益金额（元）：">
                <el-input v-model="types.dailyRate" size="small" :disabled="true" style="width: 500px" />
              </el-form-item>
            </el-form-item>
          </el-form>
        </template>
        <template v-if="item.contractType == '节能量保证型'">
          <el-form
            v-for="(el, elInd) in item?.enProjectContractTypes ?? []"
            class="u-p20 u-mt20 u-base-bg"
            :key="elInd"
            :inline="true"
            label-position="right"
            label-width="220px"
          >
            <el-form-item label="执行时段：">
              <el-input
                v-model="el[0].time"
                :placeholder="el[0].startTime + ' - ' + el[0].endTime"
                size="small"
                :disabled="true"
                style="width: 180px"
              />
            </el-form-item>
            <!-- <el-form-item label="保证：">
              <el-input
                v-model="el[0].time"
                :placeholder="el[0].ensureType === 'CONSERVATIONRATIO' ? '节能率' : '节能量'"
                size="small"
                :disabled="true"
                style="width: 180px"
              />
            </el-form-item> -->
            <br />
            <el-form-item v-for="(types, ind) in el" :key="ind">
              <el-form-item
                :label="
                  types.ensureType === 'CONSERVATIONRATIO'
                    ? '保证用' + types.keyType + '节能率（%）：'
                    : '保证用' + types.keyType + '节能量（' + types.keyTypeUnit + '）：'
                "
              >
                <el-input v-model="types.valueAmount" size="small" :disabled="true" style="width: 180px" />
              </el-form-item>
              <el-form-item :label="'保证用' + types.keyType + '节能量（' + types.keyTypeUnit + '/元）：'">
                <el-input v-model="types.valuePrice" size="small" :disabled="true" style="width: 180px" />
              </el-form-item>
            </el-form-item>
            <el-form-item label="日服务费用（元）：">
              <el-input v-model="el[0].dailyRate" size="small" :disabled="true" style="width: 180px" />
            </el-form-item>
          </el-form>
        </template>
        <el-divider></el-divider>
      </div>
      <pagination
        v-if="record?.total > 0"
        :total="record?.total ?? 0"
        :page.sync="dialogParams.pageNum"
        :limit.sync="dialogParams.pageSize"
        @pagination="getList"
        :pageSizes="[2, 5, 10]"
      />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.red {
  color: #ff0000;
}
.delete {
  width: 100%;
  height: 30px;
  cursor: pointer;
  // background-color: #374468;
}
.itemForm {
  :deep(.el-form-item__content) {
    width: 100% !important;
  }
}
.submit {
  margin-top: 20px;
  margin-left: 20px;
  margin-bottom: 20px;
}
.record {
  > div {
    margin: 10px 0;
  }
}
</style>
